package cn.edu.nwpu.warehousemanagement.service.impl;

import cn.edu.nwpu.warehousemanagement.constantEnum.OperationType;
import cn.edu.nwpu.warehousemanagement.pojo.Freight;
import cn.edu.nwpu.warehousemanagement.pojo.InventoryRecord;
import cn.edu.nwpu.warehousemanagement.pojo.Result;
import cn.edu.nwpu.warehousemanagement.dao.InventoryRecordRepository;
import cn.edu.nwpu.warehousemanagement.pojo.dto.PageDTO;
import cn.edu.nwpu.warehousemanagement.service.InventoryRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 库存记录服务实现
 * @author LSR
 */
@Service
@RequiredArgsConstructor
public class InventoryRecordServiceImpl implements InventoryRecordService {

    private final InventoryRecordRepository inventoryRecordRepository;

    @Override
    public Result<Page<InventoryRecord>> getInventoryRecordsByPage(PageDTO pageDTO) {
        // 每页固定20条记录，只查询未删除的记录
        Pageable pageable = PageRequest.of(pageDTO.getPageNum() - 1, pageDTO.getPageSize());
        Page<InventoryRecord> records = inventoryRecordRepository.findByDeletedFalse(pageable);
        return Result.success(records);
    }

    @Override
    public Result<Page<InventoryRecord>> getInboundInventoryRecordsByPage(PageDTO pageDTO) {
        Pageable pageable = PageRequest.of(pageDTO.getPageNum() - 1, pageDTO.getPageSize());
        Page<InventoryRecord> records = inventoryRecordRepository.findByTypeAndDeletedFalse(OperationType.INBOUND, pageable);
        return Result.success(records);
    }

    @Override
    public Result<Page<InventoryRecord>> getOutboundInventoryRecordsByPage(PageDTO pageDTO) {
        Pageable pageable = PageRequest.of(pageDTO.getPageNum() - 1, 20);
        Page<InventoryRecord> records = inventoryRecordRepository.findByTypeAndDeletedFalse(OperationType.OUTBOUND, pageable);
        return Result.success(records);
    }


    @Override
    public Result<InventoryRecord> getInventoryRecordById(Long id) {
        // 只查询未删除的记录
        return inventoryRecordRepository.findByIdAndDeletedFalse(id)
                .map(Result::success)
                .orElseGet(() -> Result.error("未找到对应的库存记录或记录已被删除"));
    }


    @Override
    public Result<String> getBatchIdByFreightId(Long freightId) {
        // 通过FreightId查询关联的InventoryRecord
        Optional<InventoryRecord> record = inventoryRecordRepository
                .findByFreightsIdAndDeletedFalse(freightId);

        return record.map(r -> Result.success(r.getBatchId()))
                .orElseGet(() -> Result.error("未找到对应的库存记录或批次信息"));
    }

    @Override
    @Transactional
    public Result<InventoryRecord> deleteInventoryRecord(Long id) {
        return inventoryRecordRepository.findById(id)
                .map(record -> {
                    record.setDeleted(true);
                    record.setGmtModified(LocalDateTime.now());
                    inventoryRecordRepository.save(record);
                    return Result.success(record);
                })
                .orElseGet(() -> Result.error("未找到对应的库存记录"));
    }

    @Override
    public Result<List<Freight>> getFreightsByBatchId(String batchId) {
        // 1. 根据batchId查询库存记录
        Optional<InventoryRecord> recordOpt = inventoryRecordRepository.findByBatchIdAndDeletedFalse(batchId);

        if (recordOpt.isEmpty()) {
            return Result.error("未找到对应的库存记录或记录已被删除");
        }

        // 2. 获取关联的货物列表
        InventoryRecord record = recordOpt.get();
        List<Freight> freights = record.getFreights();

        if (freights == null || freights.isEmpty()) {
            return Result.error("该批次下没有关联的货物");
        }

        return Result.success(freights);
    }

    @Override
    public Result<InventoryRecord> getInventoryRecordByBatchId(String batchId) {
        return inventoryRecordRepository.findByBatchIdAndDeletedFalse(batchId)
                .map(Result::success)
                .orElseGet(() -> Result.error("未找到批次号: " + batchId));
    }

    @Override
    public Result<Page<InventoryRecord>> getInventoryRecordsByProductName(
            String productName, OperationType operationType, PageDTO pageDTO) {
        Pageable pageable = PageRequest.of(pageDTO.getPageNum() - 1, pageDTO.getPageSize());
        Page<InventoryRecord> records = inventoryRecordRepository.findByProductNameContaining(
                productName, operationType, pageable);
        return Result.success(records);
    }
}